import { RouteRecordRaw } from "vue-router";

// 解析后端权限数据
function parseData(router: IMneuItem[], parentId: number) {
  let myRouter: IMneuItem[] = [];
  if (router) {
    let nextRoute: IMneuItem[] = [];
    router.forEach((i) => {
      if (i.parentId === parentId) {
        myRouter.push(i);
      } else {
        nextRoute.push(i);
      }
    });
    myRouter.forEach((i) => {
      i.children = [];
      i.children.push(...parseData(nextRoute, i.id));
    });
  }
  return myRouter;
}

//生成路由
function parseRoutes(routeData: IMneuItem[], parent: string = "") {
  let userRoutes: RouteRecordRaw[] = [];
  if (routeData) {
    let rootRoutes = parent ? "" : "/";
    routeData.forEach((i) => {
      let routes: RouteRecordRaw = {
        path: rootRoutes + i.name,
        name: i.name,
        component: parent
          ? () => import(`../views/${parent}/${i.name}.vue`)
          : () => import("../views/Layout.vue"),
        children: [],
      };
      userRoutes.push(routes);
      if (i.children) {
        let childrenRoutes = parseRoutes(i.children, i.name);
        routes.children = childrenRoutes;
      }
    });
  }
  return userRoutes;
}

function getDynamicRouter(router: IMneuItem[], parentId: number) {
  let routeData = parseData(router, parentId);
  let userRoutes = parseRoutes(routeData);
  return userRoutes;
}
export default getDynamicRouter;
